package com.fantabest.common.server.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.log4j.Logger;

import com.fantabest.common.PMF;
import com.fantabest.common.entity.Season;

public class SeasonDao {

	private static final Logger log = Logger.getLogger(SeasonDao.class);

	private static SeasonDao instance;

	public static SeasonDao getInstance() {
		if (instance == null)
			instance = new SeasonDao();
		return instance;
	}

	public List<Season> findAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Season.class);
		q.setOrdering("start desc");
		List<Season> results = null;
		try {
			List<Season> sqr = (List<Season>) q.execute();
			results = (List<Season>) pm.detachCopyAll(sqr);
			log.debug(results.size() + " seasons loaded from datastore");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			q.closeAll();
		}
		return results;
	}

	public Season save(Season season) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Season result = pm.makePersistent(season); 
		return pm.detachCopy(result);
	}
	
	public Season getSeasonById(Long id)	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Season season = pm.getObjectById(Season.class, id); 
		return pm.detachCopy(season); 
	}
	
	public void deleteAll()	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Season.class);
		long result = 0;
		try {
			result = q.deletePersistentAll();
			log.debug(result +" seasons deleted");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			q.closeAll();
		}
	}
	
	
	public void saveAll(List<Season> list)	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistentAll(list);
	}
}
